local h = require("null-ls.helpers")
local methods = require("null-ls.methods")

local FORMATTING = methods.internal.FORMATTING
local DIAGNOSTICS = methods.internal.DIAGNOSTICS

local M = {}
-- 获取 cjfmt 源
function M.get_cjfmt_source()
	return h.make_builtin({
		name = "cjfmt",
		meta = {
			url = "https://github.com/cangjie-lang/cjfmt",
			description = "Formatter for the Cangjie programming language",
		},
		method = FORMATTING,
		filetypes = { "Cangjie" },
		generator_opts = {
			command = "cjfmt",
			args = function(params)
				return { "-f", params.temp_path, "-o", params.temp_path }
			end,
			to_temp_file = true,
			from_temp_file = true,
		},
		factory = h.formatter_factory,
	})
end

-- 将 cjlint 输出的严重性转换为标准诊断级别
local function get_severity(severity_str, user_mapping)
	local mapping = user_mapping or { error = "warning", warning = "hint" }
	local target_severity = mapping[severity_str] or "hint"
	return h.diagnostics.severities[target_severity] or h.diagnostics.severities["hint"]
end

-- 获取 cjlint 源，根据诊断级别过滤
function M.get_cjlint_source(diagnostic_level, severity_mapping)
	return h.make_builtin({
		name = "cjlint",
		meta = {
			url = "https://github.com/cangjie-lang/cjlint",
			description = "Linter for the Cangjie programming language",
		},
		method = methods.internal.DIAGNOSTICS_ON_SAVE,
		-- methpd = null_ls.methods.DIAGNOSTICS_ON_SAVE,
		filetypes = { "Cangjie" },
		generator_opts = {
			command = "cjlint",
			args = function(params)
				local file_dir = vim.fn.fnamemodify(params.bufname, ":h")
				return {
					"-f",
					file_dir,
				}
			end,
			to_stdin = false,
			from_stdout = true,
			from_stderr = true,
			on_output = function(params, done)
				local output = params.output
				if not output or #output == 0 then
					return done({})
				end

				local diagnostics = {}
				local current_file = params.bufname
				for _, line in ipairs(vim.split(output, "\n")) do
					if line ~= "" then
						-- 去除 ANSI 颜色代码
						local clean_line = string.gsub(line, "\27%[[%d;]*m", "")

						-- 使用更简单的匹配方法
						if clean_line:find(current_file, 1, true) then
							-- 解析诊断信息
							local pattern = "([^:]+):(%d+):(%d+): (%w+): (.+)"
							local filename, line_num, col_num, severity_str, message = string.match(clean_line, pattern)

							if filename and line_num and col_num and message then
								-- 去除消息中的颜色代码（如果有）
								message = string.gsub(message, "\27%[[%d;]*m", "")

								-- 根据配置的级别过滤诊断
								local should_include = true

								-- 过滤用户指定的等级（仓颉只有error和warning）
								if diagnostic_level == "error" and severity_str ~= "error" then
									should_include = false
								end

								if should_include then
									table.insert(diagnostics, {
										row = tonumber(line_num),
										col = tonumber(col_num),
										message = "[cjlint] " .. message, -- 添加前缀标识来源
										severity = get_severity(severity_str, severity_mapping),
										source = "cjlint",
									})
								end
							end
						end
					end
				end

				return done(diagnostics)
			end,
		},
		factory = h.generator_factory,
	})
end

return M
